package com.zhonge.androiddemo.broadcast;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;

/**
 * 通过广播监听Home键
 */
public class HomeKeyListenerBroadcast extends BroadcastReceiver {
    private Context context;
    private OnHomeKeyPressListener onHomeKeyPressListener;

    private boolean isRegiested = false;

    public HomeKeyListenerBroadcast(Context context){
        this.context = context;
    }

    public HomeKeyListenerBroadcast(Context context, OnHomeKeyPressListener onHomeKeyPressListener){
        this.context = context;
        this.onHomeKeyPressListener = onHomeKeyPressListener;
    }

    public void setOnHomeKeyPressListener(OnHomeKeyPressListener onHomeKeyPressListener){
        this.onHomeKeyPressListener = onHomeKeyPressListener;
    }

    /**
     * 广播注册
     */
    public void registerSelf(){
        if(context != null){
            IntentFilter filter = new IntentFilter();
            filter.addAction(Intent.ACTION_CLOSE_SYSTEM_DIALOGS);
            context.registerReceiver(this, filter);
            isRegiested = true;
        }
    }

    /**
     * 广播UnRegister
     */
    public void unRegisterSelf(){
        if(isRegiested){
            context.unregisterReceiver(this);
            isRegiested = false;
        }
    }


    @Override
    public void onReceive(Context context, Intent intent) {
        String action = intent.getAction();
        if (Intent.ACTION_CLOSE_SYSTEM_DIALOGS.equals(action)) {
            String reason = intent.getStringExtra("reason");
            if ("homekey".equals(reason)) {
                // 按下HOME健
                if (onHomeKeyPressListener != null) {
                    onHomeKeyPressListener.onHomeKeyPress();
                }
            } else if ("recentapps".equals(reason)) {
                // 长按HOME键
                if (onHomeKeyPressListener != null) {
                    onHomeKeyPressListener.onRecentAppsKeyLongPress();
                }
            }
        }
    }

    /**
     * 事件回调接口
     */
    public interface OnHomeKeyPressListener{
        void onHomeKeyPress();
        void onRecentAppsKeyLongPress();
    }
}
